#include "gfxUnit.h"
#include <math.h>
#include <QPen>
#include <QDebug>


GFXUnit::GFXUnit(ClientEntity *entity, QGraphicsItem *parent)
   : GFXItem(entity, parent)
{
   setFlag(QGraphicsItem::ItemIsSelectable);
}


GFXUnit::GFXUnit(const EntityBaseStats &stats, QGraphicsItem *parent)
   : GFXItem(stats, parent)
{
   setFlag(QGraphicsItem::ItemIsSelectable);
}


GFXUnit::~GFXUnit()
{
}


QRectF GFXUnit::boundingRect() const
{
   qreal penWidth = 1;
   return QRectF(-10 - penWidth / 2, -10 - penWidth / 2, 20 + penWidth, 20 + penWidth);
}


void GFXUnit::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
   if (mUseEntity)
   {
      if (mEntity) doPaint(mEntity->base.color,
                           mEntity->health/10,
                           mEntity->base.kind,
                           mSquadSize,
                           *painter,
                           mPulsate ? mPulsateScale : 1.0);
   }
   else
   {

      doPaint(mStats.color,
              mStats.size,
              mStats.kind,
              mSquadSize,
              *painter,
              mPulsate ? mPulsateScale : 1.0);
   }
}


void GFXUnit::tick()
{
   GFXItem::tick();

   if (mUseEntity && mEntity)
      setPos(mEntity->pos.toPointF());
}


void GFXUnit::doPaint(const QColor &color, const qint32 size, const qint32 sides, const qint32 squadSize, QPainter& painter, const qreal scale)
{
  painter.save();
  QPen pen(color);
  qint32 newSize;
  if (size <= UNIT_SIZE_THRESHOLD)
  {
     newSize = 2.5*size;
     pen.setWidth(1);
  }
  else
  {
     newSize = 2.5*UNIT_SIZE_THRESHOLD;
     pen.setWidth((size-UNIT_SIZE_THRESHOLD)*2);
  }
  newSize += 4;

  painter.setPen(pen);

  QVector<QPointF> points;
  for (qint32 i(0); i<sides; ++i)
  {
     qreal x(newSize * cos((i/(float)sides*360.0*M_PI/180.0-M_PI))),
           y(newSize * sin((i/(float)sides*360*M_PI/180.0-M_PI)));
     points << QPointF(x, y);
  }

  painter.scale(scale, scale);
  painter.drawPolygon(points);

  if (squadSize > 1)
  {
     painter.scale(1/scale, 1/scale);
     painter.translate(-24, 26);
     painter.setFont(QFont("VERDANA", 8));
     painter.drawText(0, 0, "x"+QString::number(squadSize));
  }
   painter.restore();
}
